// utils/imagePreprocessor.ts
export class ImagePreprocessor {
  /**
   * 将 Markdown 中的所有图片转换为 Base64
   */
  static async convertImagesToBase64(markdownText: string): Promise<string> {
    let processedText = markdownText;
    
    // 匹配 Markdown 图片语法
    const imageRegex = /!\[(.*?)\]\((.*?)\)/g;
    const matches = [...markdownText.matchAll(imageRegex)];
    
    for (const match of matches) {
      const fullMatch = match[0];
      const altText = match[1];
      const imageUrl = match[2];
      
      try {
        const base64Image = await this.urlToBase64(imageUrl);
        if (base64Image) {
          const base64Markdown = `![${altText}](${base64Image})`;
          processedText = processedText.replace(fullMatch, base64Markdown);
        }
      } catch (error) {
        console.warn(`无法转换图片: ${imageUrl}`, error);
        // 如果转换失败，保留原图片链接
      }
    }
    
    return processedText;
  }

  /**
   * 将图片 URL 转换为 Base64
   */
  private static async urlToBase64(url: string): Promise<string | null> {
    try {
      // 如果是 data URL，直接返回
      if (url.startsWith('data:')) {
        return url;
      }

      let response: Response;
      
      // 尝试直接请求
      try {
        response = await fetch(url, { mode: 'cors' });
      } catch (error) {
        // 如果直接请求失败，尝试使用代理
        const proxyUrl = this.getProxyUrl(url);
        response = await fetch(proxyUrl);
      }
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      
      const blob = await response.blob();
      return await this.blobToBase64(blob);
    } catch (error) {
      console.warn(`转换图片为 Base64 失败: ${url}`, error);
      return null;
    }
  }

  /**
   * 获取 CORS 代理 URL
   */
  private static getProxyUrl(url: string): string {
    // 使用多个 CORS 代理服务作为备选
    const proxies = [
      `${encodeURIComponent(url)}`,
      `${encodeURIComponent(url)}`,
      `${url}`
    ];

    console.log(proxies);
    
    return proxies[0]; // 使用第一个代理
  }

  /**
   * Blob 转 Base64
   */
  private static blobToBase64(blob: Blob): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        if (typeof reader.result === 'string') {
          resolve(reader.result);
        } else {
          reject(new Error('转换失败'));
        }
      };
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  }

  /**
   * 检查图片是否可访问
   */
  static async checkImageAccessibility(url: string): Promise<boolean> {
    try {
      const response = await fetch(url, { method: 'HEAD', mode: 'no-cors' });
      return true;
    } catch (error) {
      try {
        const proxyUrl = this.getProxyUrl(url);
        const response = await fetch(proxyUrl, { method: 'HEAD' });
        return response.ok;
      } catch (proxyError) {
        return false;
      }
    }
  }
}